package com.cizzy.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cizzy.user.common.Result;
import com.cizzy.user.entity.UserCount;
import com.cizzy.user.mapper.UserCountMapper;
import com.cizzy.user.service.IUserCountService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author crissy-月下闲人
 * @since 2023-10-29
 */
@Service
public class UserCountServiceImpl extends ServiceImpl<UserCountMapper, UserCount> implements IUserCountService {

    @Resource
    private UserCountMapper userCountMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public synchronized void createUserCountById(Long id) {
        if (id == null) {
            return;
        }
        UserCount userCount = new UserCount(id);
        int result = userCountMapper.insert(userCount);
        if (result > 0) {
            Result.success();
        } else {
            Result.error("用户计数创建失败");
        }
    }

    @Override
    public Result<UserCount> getUserCountByUserId(Long userId) {
        QueryWrapper<UserCount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        UserCount userCount = userCountMapper.selectOne(queryWrapper);
        if(userCount != null) {
            return Result.success(userCount);
        } else {
            return Result.error("用户计数不存在");
        }
    }

    @Override
    public Result<List<UserCount>> getUserCountListByUserIds(List<Long> userIdList) {
//        List<UserCount> userCountList = userCountMapper.selectBatchIds(userIdList);
        List<UserCount> userCountList = userIdList.stream().map(userId -> {
            UserCount userCount = userCountMapper.selectById(userId);
            return userCount;
        }).collect(Collectors.toList());
        return Result.success(userCountList);
    }

    @Override
    public Result<UserCount> addUserCountById(String column, Long id, int num) {
        UpdateWrapper<UserCount> updateWrapper = new UpdateWrapper<>();
        updateWrapper.
                setSql(column + " = " + column + " + " + num).
                eq("user_id", id);
        int result = userCountMapper.update(null, updateWrapper);
        if (result > 0) {
            return Result.success();
        } else {
            return Result.error("视频计数更新失败");
        }
    }
}
